//
/**
 * Filename: fig10-6_sigcld.c
 * Author:   csbonkers
 * Contact:  forever65535@qq.com
 * Date:     2021/6/19
 * Description:
 *    
 */
#include "apue.h"
#include <sys/wait.h>

static void sig_cld(int signo);

int main(int argc, char *argv[]) {
  pid_t pid;
  if (signal(SIGCLD, sig_cld) == SIG_ERR) {
    perror("signal error");
  }
  if ((pid = fork()) < 0) {
    perror("fork error");
  } else if (pid == 0) {
    // child
    sleep(2);
    _exit(0);
  }
  // parent
  pause();
  return 0;
}

void sig_cld(int signo) {
  pid_t pid;
  int status;
  printf("SIGCLD received\n");
  if (signal(SIGCLD, sig_cld) == SIG_ERR) {// reestablish handler
    perror("signal error");
  }
  if ((pid = wait(&status)) < 0) {// fetch child status
    perror("wait error");
  }
}